﻿function log() {
  document.getElementById('results').innerText = '';

  Array.prototype.forEach.call(arguments,
    function (msg) {
      if (msg instanceof Error) {
        msg = "Error: " + msg.message;
      } else if (typeof msg != 'string') {
        msg = JSON.stringify(msg, null, 2);
      }
      document.getElementById('results').innerHTML += msg + '\r\n';
    });
}

document.getElementById("login").addEventListener("click", login, false);
document.getElementById("api").addEventListener("click", api, false);
document.getElementById("logout").addEventListener("click", logout, false);

var config = {
  authority: "https://wx.cq.abchina.com/test/authorize/", // 统一登录地址
  client_id: "test",
  redirect_uri: "http://localhost:5003/callback.html", // 登录成功后回调地址
  response_type: "id_token token",
  scope: "openid profile api1", // 访问域
  post_logout_redirect_uri: "http://localhost:5003/index.html" // 登出回调地址
};

var mgr = new Oidc.UserManager(config);
var global_user;

mgr.getUser().then(function (user) {
  if (user) {
    global_user = user;
    log("User logged in", user.profile);
  }
  else {
    log("User not logged in");
  }
});

function login() {
  mgr.signinRedirect();
}

function api() {
  if (!global_user) {
    mgr.signinRedirect();
  }
  mgr.getUser().then(function (user) {
    if (user) {
      // 已登录
      var url = "http://localhost:5004/identity"; // 请求web api 地址

      var xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.onload = function() {
        log(xhr.status, JSON.parse(xhr.responseText));
      }
      xhr.setRequestHeader("Authorization", "Bearer " + user.access_token);
      xhr.send();
    } else {
      // 未登录 
      mgr.signinRedirect();
    }

  });
}

function logout() {
  mgr.signoutRedirect();
}